package org.gpf;

import java.io.File;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

public class SAX_Test {
	
	public static void main(String[] args) throws Exception {
		saxParser("res/books.xml");
	}

	public static void saxParser(String url) throws Exception, SAXException{
		
		SAXParserFactory sf = SAXParserFactory.newInstance();	// 得到SAXParserFactory
		SAXParser parser = sf.newSAXParser();					//得到SAXParser，通过SAXParserFactory
		parser.parse(new File(url), new SAXHandler());			// 用SAXParser.parse(File f,DefaultHandler dh)解析xml
	}
	
}

class SAXHandler extends DefaultHandler{
	
	@Override
	public void startDocument() throws SAXException {
		System.out.println("=========== SAX解析开始 ==========");
		System.out.println("<?xml version = 1.0 encoding = \"utf-8\"?>");
	}
	
	@Override
	public void endDocument() throws SAXException {
		System.out.println("\n=========== SAX解析结束 ==========");
	}
	
	@Override
	public void startElement(String uri, String localName, String qName,
			Attributes attributes) throws SAXException {
		System.out.print("<" + qName);
		// 解析属性
		if (attributes != null) {
			for (int i = 0; i < attributes.getLength(); i++) {
				System.out.print(" " + attributes.getQName(i) + " = \"" + attributes.getValue(i) + "\"");
			}
		}
		System.out.print(">");
	}
	
	@Override
	public void endElement(String uri, String localName, String qName)
			throws SAXException {
		System.out.print("</" + qName);
		System.out.print(">");
	}
	
	/**
	 * 遇到文本
	 */
	@Override
	public void characters(char[] ch, int start, int length)
			throws SAXException {
		System.out.print(new String(ch, start, length));
	}
}